package com.bz.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import com.bz.common.Codeenum;
import com.bz.common.ResponseDto;
import com.bz.common.ResponseUtils;
import com.bz.model.MokData;

@Component
public class ApiMesInterceptor implements HandlerInterceptor {

    @Autowired
    private MokData mokData;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String test = request.getHeader("test");
        if (StringUtils.equals(test, "1")) {
            String uri = request.getRequestURI();
            uri = uri.substring(uri.lastIndexOf("/") + 1);

            // 未登录，返回登陆页
            String data = mokData.getData().get(uri);
            ResponseDto a = new ResponseDto(Codeenum.REMOTE_DATA.getCode(), Codeenum.REMOTE_DATA.getMsg());
            if (StringUtils.isEmpty(data)) {
                a.setData("无mok数据");
            } else {
                if (data.startsWith("[")) {
                    a.setData(JSON.parseArray(data));
                } else if (data.startsWith("{")) {
                    a.setData(JSON.parseObject(data));
                } else {
                    a.setData(data);
                }
            }

            ResponseUtils.setResponse(response, a);
            return false;
        }

        return true;
    }
}
